import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import {AppService} from '../app.service';
import {catchError, tap} from 'rxjs/operators';
import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd';
import {LoginDto} from './basic.model';
import {BasicService} from './basic.service';

@Injectable()
export class BaseHttpInterceptor implements HttpInterceptor {
  constructor(private router: Router,
              public appService: AppService,
              public basicService: BasicService,
              private message: NzMessageService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let headers = null;
    const login: LoginDto = this.basicService.getRefreshToken();
    if (login) {
      headers = req.headers.set('token', login.accessToken ? login.accessToken : '');
    }
    const authReq = req.clone({headers});
    return next.handle(authReq).pipe(
      catchError((err) => {
        if (err.error.code === 'tokenExpire') {
          const loginDto: LoginDto = this.basicService.getRefreshToken(true);
          if (loginDto) {
            const auth = req.clone({headers: req.headers.set('token', loginDto.accessToken)});
            return next.handle(auth).pipe();
          }
        }
        throw err;
      }),
      tap(res => {
        return res;
      }, err => {
        this.appService.setLoading(false);
        if (err && err.error && err.error.message) {
          this.message.error(err.error.message);
        } else {
          console.error(err);
        }
        if (err.status === 400 && err.error.code === 'tokenExpire') {
          this.basicService.logOut();
        }
      }));
  }


}
